/**
 * 
 */
package gpl.androidcommons.service;

import java.util.LinkedList;
import java.util.List;

import android.util.Log;

/**
 * @author Norbert
 * @param <T>
 */
public abstract class ScheduleService<T> implements Runnable {

  private static final String TAG = ScheduleService.class.toString();

  private final List<ScheduleServiceListener<T>> listeners = new LinkedList<ScheduleServiceListener<T>>();

  public ScheduleService() {
  }

  public ScheduleService(ScheduleServiceListener<T> listener) {
    listeners.add(listener);
  }

  @Override
  public final void run() {
    try {
      fireJobFinished(perform());
    } catch (Exception e) {
      fireJobFailed(e);
    }
  }

  protected abstract T perform() throws Exception;

  /**
   * Notify 
   */
  protected void fireJobFinished(T result) {
    Log.d(TAG, "fireJobFinished");
    for (ScheduleServiceListener<T> listener : listeners) {
      listener.done(result);
    }
  }

  /**
   * @param e
   */
  protected void fireJobFailed(Exception e) {
    Log.d(TAG, "fireJobFailed " + e.getLocalizedMessage(), e);
    for (ScheduleServiceListener<T> listener : listeners) {
      listener.failed(e);
    }
  }

  /**
   * @param listener
   */
  public void addListener(ScheduleServiceListener<T> listener) {
    Log.d(TAG, "addListener " + listener);
    listeners.add(listener);
  }

  /**
   * @param listener
   */
  public void removeListener(ScheduleServiceListener<T> listener) {
    Log.d(TAG, "removeListener " + listener);
    listeners.remove(listener);
  }

}
